package com.toraeve.asktora.security.entity;

import java.util.Collection;
import java.util.HashSet;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.toraeve.asktora.domain.entity.ToraUser;

/**
 * A adapter(<i>follows the standard adapter design pattern</i>) between domain
 * entity <code>ToraUser</code> and Spring Security <code>UserDetails</code>
 * 
 * @author larry.li
 * 
 */
public class ToraUserDetailsAdapter implements UserDetails {

	private static final long serialVersionUID = 1L;

	private ToraUser user;
	private Collection<GrantedAuthority> authorities;

	public ToraUserDetailsAdapter(ToraUser user) {
		this.user = user;
		authorities = new HashSet<GrantedAuthority>();
		for (String roleName : user.getRole()) {
			authorities.add(new SimpleGrantedAuthority(roleName));
		}
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return authorities;
	}

	@Override
	public String getPassword() {
		return user.getPassword();
	}

	/**
	 * <strong>&lt;IMPORTANT!&gt;</strong> this method actually returns the
	 * <code>email</code> property of <code>ToraUser</code> coz in my design,
	 * instead username, the email is the real unique id in whole system
	 * 
	 * @see org.springframework.security.core.userdetails.UserDetails#getUsername()
	 */
	@Override
	public String getUsername() {
		return user.getEmail();
	}

	@Override
	public boolean isAccountNonExpired() {
		return !user.isExpired();
	}

	@Override
	public boolean isAccountNonLocked() {
		return !user.isLocked();
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return !user.isCredentialsExpired();
	}

	@Override
	public boolean isEnabled() {
		return user.isEnabled();
	}

	public ToraUser getUser() {
		return user;
	}
}
